import re
import tkinter as tk
from imaplib import IMAP4_SSL
from logging.config import valid_ident
from tkinter import messagebox
from tkinter.messagebox import askokcancel

from pygame.examples.go_over_there import screen

#创建主窗体
root = tk.Tk()
root.title("登录")
#获取设备的宽高
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
window_width=500
window_height=300
x=(screen_width - window_width)//2
y=(screen_height- window_height)//2#双斜杠表示整除
root.geometry(f"{window_width}x{window_height}+{x}+{y}")#宽x高，两个加号用来确定放置的位置相当于横纵轴
root.config(pady=50)#表示上下内边距

#创建一个按钮
# login_btn=tk.Button(root,text="登录",width=10)
# #login_btn.pack()#表示按照添加顺序排列组件
# login_btn.grid(row=0,column=0)
# login_btn2=tk.Button(root,text="登录2",width=10)
# login_btn2.grid(row=0,column=1)
# login_btn3=tk.Button(root,text="登录3",width=10)
# login_btn3.grid(row=1,column=0)
# login_btn4=tk.Button(root,text="登录4",width=10)
# login_btn4.grid(row=1,column=1)

tk.Label(root,text="用户名",width=27,anchor="e").grid(row=0, column=0)
username=tk.Entry(root,width=20,validate="focusout",validatecommand=lambda:checkUserName())
username.grid(row=0, column=1)
lbl_username=tk.Label(root,text="",width=15,bg="red")
lbl_username.grid(row=0, column=2)

tk.Label(root,text="",width=27,anchor="e").grid(row=1, column=0)

tk.Label(root,text="密 码",width=27,anchor="e").grid(row=2, column=0)
pwd=tk.Entry(root,width=20)
pwd.grid(row=2, column=1)
lbl_pwd=tk.Label(root,text="",width=15,bg="red")
lbl_pwd.grid(row=2, column=2)

tk.Label(root,text="",width=27,anchor="e").grid(row=3, column=0)

tk.Label(root,text="",width=17,anchor="e").grid(row=4, column=0)


login_btn=tk.Button(root,text="登录",width=10,command=lambda:login() )
login_btn.grid(row=4,column=1)

login_btn=tk.Button(root,text="退出",width=10,command=lambda:logout() )
login_btn.grid(row=4,column=2)

def login():
    str_name=username.get().strip()
    str_pwd=pwd.get().strip()
    if str_name=="admin" and str_pwd=="123456":
        messagebox.showinfo("提示","登录成功")
    else:
        messagebox.showwarning("提示","用户名或密码错误")


def logout():
    result=messagebox.askokcancel("提示","确定退出吗？")
    if result:
        root.quit()
    else:
        pass

def checkUserName():
    name = username.get().strip()
    # 用户名为空，跳过验证
    if not name:
        return True
    else:
        # 判断用户名格式
        if not re.match(r'^[a-zA-Z0-9_-]{4,16}$', name):
            lbl_username.config(text='用户名格式不正确', fg='white')
            return False  # 验证失败返回False
        else:
            lbl_username.config(text='')
            return True



root.mainloop()#放置最后